﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DormMS.IService;
using SqlSugar;
using Infrastructure;
using Infrastructure.Tool;
using Infrastructure.Pub;
using DormMS.Model;
using DormMS.Model.ViewModels;
using System.Text;
using DormMS.Common;
using Newtonsoft.Json;

namespace DormMS.Controllers
{

    public class AccountController : Controller
    {
        private IUserInfoService _userService;
        private IDepartmentService _departmentService;
        //用户第一次登录初始密码是123456
        private string initPwd = "E10ADC3949BA59ABBE56E057F20F883E";

        public AccountController(IUserInfoService userService, IDepartmentService detpartmentService)
        {
            _userService = userService;
            _departmentService = detpartmentService;
        }

        public ActionResult Login()
        {
            return View();
        }

        public JsonResult LoginSubmit(string userName, string passWord, string validateCode)
        {
            Result result = new Result();
            try
            {
                if (userName.IsNullOrEmpty())
                {
                    result.msg = "请输入用户名";
                }
                else if (passWord.IsNullOrEmpty())
                {
                    result.msg = "请输入密码";
                }
                else if (validateCode.ToUpper() != Session["ValidateCode"].ToString().ToUpper())
                {
                    result.msg = "输入验证码不正确";
                }
                else
                {
                    var user = _userService.GetUserInfo(userName);
                    if (user != null)
                    {
                        if (user.UserState == 1)
                        {
                            result.msg = "该用户已被冻结";
                        }
                        else
                        {
                            if (user.Password == Generator.MD5(passWord))
                            {
                                result.isSuccess = true;
                                Generator.SetCookie(PubConst.CookieUserKey, user.Id.ToString());
                                string uniqueKey = string.Format(PubConst.CacheUserKey, user.Id.ToString());

                                CacheManager<CacheUserInfo>.GetInstance().Add(uniqueKey, user, int.MaxValue);
                                result.msg = "登录成功，正跳转...";
                            }
                            else
                            {
                                result.msg = "用户名密码不正确";
                            }
                        }
                    }
                    else
                    {
                        //result.msg = "用户名密码不正确";
                        //接口处理登录学生信息处理
                        var type = "utf-8";
                        var tKey = WsdConfig.GetAppString("tKey");
                        var Url = "http://stubase.ccit.js.cn/interfacejson/InterFace_StuList.aspx?stuno=" + userName + "&tkey=" + tKey;

                        System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
                        // Get the response instance.
                        System.Net.WebResponse wResp = wReq.GetResponse();
                        System.IO.Stream respStream = wResp.GetResponseStream();
                        // Dim reader As StreamReader = New StreamReader(respStream)
                        string studentData = "";
                        using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))
                        {
                            studentData = reader.ReadToEnd();
                        }

                        //使用Newtonsoft.Json.JsonConvertDeserializeObject<dynamic>(data)动态的数据转换成;
                        //var userinfo1 = JsonConvert.DeserializeObject<dynamic>(data);
                        //foreach (var user1 in userinfo1.StuList)
                        //{
                        //    处理过程
                        //}
                        //使用实体对象转换
                        var studentInfo = JsonHelper.FromJson<StudentList>(studentData);

                        if (studentInfo != null && studentInfo.StuList.Count > 0)
                        {
                            //判断初始密码是不是123456
                            if (initPwd == passWord)
                            {
                                result.isSuccess = true;
                                Generator.SetCookie(PubConst.CookieUserKey, user.Id.ToString());
                                string uniqueKey = string.Format(PubConst.CacheUserKey, user.Id.ToString());

                                CacheManager<CacheUserInfo>.GetInstance().Add(uniqueKey, user, int.MaxValue);
                                //登录成功后向userinfo表插入数据
                                UserInfo stuUserInfo = new UserInfo();
                                stuUserInfo.UserName = studentInfo.StuList[0].Stu_Base_ID;
                                stuUserInfo.Password = initPwd;
                                stuUserInfo.GroupId = 0;
                                stuUserInfo.DepartmentId = _departmentService.getDepartmentByName(studentInfo.StuList[0].Stu_School_Departmentname).Id;
                                stuUserInfo.RealName = studentInfo.StuList[0].Stu_Base_Name;
                                stuUserInfo.IsTeacher = 0;
                                stuUserInfo.DynamicPassword = "";
                                if (studentInfo.StuList[0].Stu_Base_Sex == "男")
                                {
                                    stuUserInfo.Sex = 1;
                                }
                                else
                                {
                                    stuUserInfo.Sex = 2;
                                }

                                _userService.UserEditSubmit(stuUserInfo, 0);

                                result.msg = "登录成功，正跳转...";

                            }
                            else
                            {
                                result.msg = "用户名密码不正确！";
                            }
                        }
                        else
                        {
                            //接口处理登录老师信息处理
                            var Url1 = "http://stubase.ccit.js.cn/interfacejson/InterFace_TeacherList.aspx?teachernum=" + userName + "&tkey=" + tKey;
                            wReq = System.Net.WebRequest.Create(Url1);
                            // Get the response instance.
                            wResp = wReq.GetResponse();
                            respStream = wResp.GetResponseStream();
                            // Dim reader As StreamReader = New StreamReader(respStream)
                            string teacherData = "";
                            using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))
                            {
                                teacherData = reader.ReadToEnd();
                            }

                            //使用Newtonsoft.Json.JsonConvertDeserializeObject<dynamic>(data)动态的数据转换成;
                            //var userinfo1 = JsonConvert.DeserializeObject<dynamic>(data);
                            //foreach (var user1 in userinfo1.StuList)
                            //{
                            //    处理过程
                            //}
                            //使用实体对象转换
                            var teacherInfo = JsonHelper.FromJson<TeacherList>(teacherData);

                            if (teacherInfo != null && teacherInfo.TeaList.Count > 0)
                            {
                                //判断初始密码是不是123456
                                if (initPwd == passWord)
                                {
                                    result.isSuccess = true;
                                    Generator.SetCookie(PubConst.CookieUserKey, user.Id.ToString());
                                    string uniqueKey = string.Format(PubConst.CacheUserKey, user.Id.ToString());

                                    CacheManager<CacheUserInfo>.GetInstance().Add(uniqueKey, user, int.MaxValue);

                                    //第一次登录向userinfo表插入数据
                                    UserInfo teacherUserInfo = new UserInfo();
                                    teacherUserInfo.UserName = teacherInfo.TeaList[0].Base_Teacher_Code;
                                    teacherUserInfo.Password = initPwd;
                                    teacherUserInfo.GroupId = 0;
                                    teacherUserInfo.DepartmentId = _departmentService.getDepartmentByName(studentInfo.StuList[0].Stu_School_Departmentname).Id;
                                    teacherUserInfo.RealName = teacherInfo.TeaList[0].Base_Teacher_Name;
                                    teacherUserInfo.IsTeacher = 1;
                                    teacherUserInfo.DynamicPassword = "";
                                    //接口中老师信息没有性别，都默认为男
                                    teacherUserInfo.Sex = 1;

                                    _userService.UserEditSubmit(teacherUserInfo, 0);

                                    result.msg = "登录成功，正跳转...";
                                }
                                else
                                {
                                    result.msg = "用户名密码不正确！";
                                }
                            }
                            else
                            {
                                result.msg = "用户信息不存在，请联系学工处！";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult GetUserInfo(string userName)
        {
            string uid = Generator.GetCookie(PubConst.CookieUserKey);
            if (uid.IsNullOrEmpty())
            {
                return Json(_userService.GetUserInfo(userName));
            }

            string uniqueKey = string.Format(PubConst.CacheUserKey, uid);
            var user = _userService.GetCacheUser();
            if (user == null || user.Id == 0)
            {
                user = _userService.GetUserInfo(userName);
            }
            return Json(user);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ChangePassword()
        {
            return View();
        }


        [HttpPost]
        public ActionResult GetAppSetting()
        {
            return Json(new { ImgUploadUrl = WsdConfig.GetAppString("ImgUploadUrl"), ImgHostUrl = WsdConfig.GetAppString("ImgHostUrl"), WapHostUrl = WsdConfig.GetAppString("WapHostUrl") });
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult GetValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(4);
            Session["ValidateCode"] = code;
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }
    }
}